package com.cia.blockchain.controller;

import com.cia.blockchain.model.Chaincode;
import com.cia.blockchain.service.Blockchainservice;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.client.protocol.response.BlockNumber;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/blockchain")
@RestController
public class BlockchainController {
    @Resource
    private Blockchainservice blockchainservice;

    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";


    @GetMapping("/get")
    public String getValue(@RequestParam String key, HttpServletRequest request,
                           HttpServletResponse response) {
        // 基本的认证
        System.out.println("收到id = " + key);
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        Chaincode read = blockchainservice.read(key);
        System.out.println("查到消息" + read.getValue());

        return read.getValue();
    }

    @PostMapping("/set")
    public String set(@RequestBody Chaincode chaincode, HttpServletRequest request,
                      HttpServletResponse response){
        // 基本的认证
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        System.out.println("收到消息" + chaincode.toString());
        boolean res = blockchainservice.write(chaincode);
        if(res){
            return "success";
        }
        return "fail";
    }
}
